<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }} - 文档查看器</title>
    <!-- PDF.js 使用 cdnjs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.min.js"></script>
    <!-- 添加Word文档查看库 mammoth.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.0/mammoth.browser.min.js"></script>
    <!-- 添加Excel文档查看库 SheetJS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #5E2D9B;
            color: white;
            padding: 15px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header h1 {
            font-size: 18px;
            margin: 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 70%;
        }
        .header-actions a {
            color: white;
            text-decoration: none;
            margin-left: 15px;
            font-size: 14px;
        }
        .header-actions a:hover {
            text-decoration: underline;
        }
        .viewer-container {
            position: absolute;
            top: 60px;
            left: 0;
            right: 0;
            bottom: 0;
            overflow: hidden;
        }
        /* PDF查看器样式 */
        #pdf-viewer {
            width: 100%;
            height: 100%;
            display: none;
            text-align: center;
            overflow: auto;
        }
        /* Office文档查看器样式 */
        #office-viewer {
            width: 100%;
            height: 100%;
            border: none;
            display: none;
            background-color: white;
            overflow: auto;
            padding: 0;
            box-sizing: border-box;
            text-align: center;
        }
        /* 备用查看器样式 */
        #fallback-viewer {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            display: none;
        }
        .fallback-message {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
            max-width: 500px;
        }
        .fallback-message h2 {
            margin-top: 0;
            color: #333;
            font-size: 22px;
        }
        .fallback-message p {
            color: #666;
            margin-bottom: 20px;
            font-size: 16px;
        }
        .download-btn {
            background-color: #5E2D9B;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            text-decoration: none;
            font-size: 16px;
            cursor: pointer;
        }
        .download-btn:hover {
            background-color: #4A2379;
        }
        /* Excel表格样式 */
        .excel-table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        .excel-table th, .excel-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .excel-table th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .excel-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        /* Word文档样式 */
        .word-document {
            max-width: 800px;
            margin: 0 auto;
            line-height: 1.6;
            color: #333;
        }
        .word-document h1, .word-document h2, .word-document h3 {
            color: #333;
        }
        .word-document table {
            border-collapse: collapse;
            margin: 15px 0;
        }
        .word-document table, .word-document th, .word-document td {
            border: 1px solid #ddd;
        }
        .word-document th, .word-document td {
            padding: 8px 12px;
        }
        /* 加载指示器 */
        .loading-indicator {
            text-align: center;
            padding: 30px;
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #5E2D9B;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        /* 其他紫色相关样式 */
        .sheet-tab {
            border-bottom: 2px solid #5E2D9B;
        }
        /* 通用文档内容容器 */
        .doc-content-container {
            max-width: 90%;
            width: 900px;
            margin: 0 auto;
            padding: 20px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>{{ title }}</h1>
        <div class="header-actions">
            <a href="{{ doc_url }}" download>下载文档</a>
        </div>
    </div>
    
    <div class="viewer-container">
        <!-- PDF查看器 -->
        <div id="pdf-viewer"></div>
        
        <!-- Office文档查看器 -->
        <div id="office-viewer"></div>
        
        <!-- 备用查看器（无法直接预览时使用） -->
        <div id="fallback-viewer">
            <div class="fallback-message">
                <h2>无法直接预览此文档</h2>
                <p>此类型的文档不支持在线预览，请下载后查看。</p>
                <a href="{{ doc_url }}" download class="download-btn">下载文档</a>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const fileType = '{{ file_type }}';
            const docUrl = '{{ doc_url }}';
            const fileName = '{{ file_name }}';
            
            // 根据文件类型选择查看器
            if (fileType === 'pdf') {
                // 使用PDF.js查看PDF
                loadPdfViewer(docUrl);
            } else if (['doc', 'docx'].includes(fileType)) {
                // 使用mammoth.js查看Word文档
                loadWordViewer(docUrl, fileType);
            } else if (['xls', 'xlsx'].includes(fileType)) {
                // 使用SheetJS查看Excel文档
                loadExcelViewer(docUrl, fileType);
            } else if (['ppt', 'pptx'].includes(fileType)) {
                // PowerPoint暂时没有好的纯JS解析库，使用备用查看器
                showFallbackViewer("PowerPoint格式文件暂不支持在线预览，请下载后查看。");
            } else {
                // 不支持直接查看的文件类型
                showFallbackViewer("此类型文件不支持在线预览，请下载后查看。");
            }
            
            // PDF查看器
            function loadPdfViewer(url) {
                const pdfViewer = document.getElementById('pdf-viewer');
                pdfViewer.style.display = 'block';
                
                // 使用PDF.js加载PDF
                pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.4.120/pdf.worker.min.js';
                
                // 创建中心容器
                const centerContainer = document.createElement('div');
                centerContainer.className = 'doc-content-container';
                centerContainer.style.display = 'flex';
                centerContainer.style.flexDirection = 'column';
                centerContainer.style.alignItems = 'center';
                centerContainer.style.justifyContent = 'flex-start';
                
                // 直接使用PDF.js内置的API加载PDF
                pdfjsLib.getDocument(url).promise.then(function(pdf) {
                    // 创建一个简单的PDF查看容器
                    const container = document.createElement('div');
                    container.style.width = '100%';
                    container.style.display = 'flex';
                    container.style.flexDirection = 'column';
                    container.style.alignItems = 'center'; // 水平居中
                    container.style.padding = '20px';
                    container.style.backgroundColor = '#f8f9fa';
                    container.style.boxSizing = 'border-box';
                    
                    // 记录要加载的页数和已加载的页数
                    const maxPages = Math.min(pdf.numPages, 10);
                    let loadedPages = 0;
                    
                    // 加载前10页
                    for (let pageNum = 1; pageNum <= maxPages; pageNum++) {
                        pdf.getPage(pageNum).then(function(page) {
                            const scale = 1.5;
                            const viewport = page.getViewport({scale: scale});
                            
                            // 创建页面容器
                            const pageContainer = document.createElement('div');
                            pageContainer.style.position = 'relative';
                            pageContainer.style.marginBottom = '20px';
                            pageContainer.style.border = '1px solid #ddd';
                            pageContainer.style.borderRadius = '4px';
                            pageContainer.style.boxShadow = '0 1px 3px rgba(0,0,0,0.1)';
                            pageContainer.style.backgroundColor = 'white';
                            pageContainer.style.width = viewport.width + 'px';
                            pageContainer.style.height = viewport.height + 'px';
                            
                            // 创建canvas
                            const canvas = document.createElement('canvas');
                            const context = canvas.getContext('2d');
                            canvas.width = viewport.width;
                            canvas.height = viewport.height;
                            
                            // 添加页码
                            const pageInfo = document.createElement('div');
                            pageInfo.textContent = `第 ${pageNum} 页 / 共 ${pdf.numPages} 页`;
                            pageInfo.style.textAlign = 'center';
                            pageInfo.style.marginTop = '5px';
                            pageInfo.style.marginBottom = '15px';
                            pageInfo.style.color = '#666';
                            
                            // 渲染页面
                            const renderContext = {
                                canvasContext: context,
                                viewport: viewport
                            };
                            
                            pageContainer.appendChild(canvas);
                            // 先添加页面，再添加页码信息
                            container.appendChild(pageContainer);
                            container.appendChild(pageInfo);
                            
                            page.render(renderContext);
                            
                            loadedPages++;
                            
                            // 当所有页面渲染完毕时，才添加下载提示
                            if (loadedPages === maxPages) {
                                // 如果总页数超过显示的页数，才显示提示信息
                                if (pdf.numPages > 10) {
                                    const moreInfo = document.createElement('div');
                                    moreInfo.style.padding = '20px';
                                    moreInfo.style.backgroundColor = 'white';
                                    moreInfo.style.textAlign = 'center';
                                    moreInfo.style.borderRadius = '4px';
                                    moreInfo.style.marginTop = '20px';
                                    moreInfo.style.width = '100%';
                                    moreInfo.innerHTML = `
                                        <p>文档共 ${pdf.numPages} 页，此处仅显示前10页预览。</p>
                                        <a href="${url}" download class="download-btn" style="display:inline-block;">下载完整文档</a>
                                    `;
                                    container.appendChild(moreInfo);
                                }
                            }
                        });
                    }
                    
                    centerContainer.appendChild(container);
                    pdfViewer.appendChild(centerContainer);
                }).catch(function(error) {
                    console.error('无法加载PDF:', error);
                    showFallbackViewer();
                });
            }
            
            // Word文档查看器
            function loadWordViewer(url, fileType) {
                const officeViewer = document.getElementById('office-viewer');
                officeViewer.style.display = 'block';
                
                // 显示加载指示器
                const loadingIndicator = document.createElement('div');
                loadingIndicator.className = 'loading-indicator';
                loadingIndicator.innerHTML = `
                    <div class="loading-spinner"></div>
                    <p>正在加载文档，请稍候...</p>
                `;
                officeViewer.appendChild(loadingIndicator);
                
                // 只有docx格式可以用mammoth解析
                if (fileType === 'docx') {
                    // 获取文档内容
                    fetch(url)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('无法加载文档');
                            }
                            return response.arrayBuffer();
                        })
                        .then(arrayBuffer => {
                            // 使用mammoth.js将Word文档转换为HTML
                            return mammoth.convertToHtml({ arrayBuffer: arrayBuffer });
                        })
                        .then(result => {
                            // 移除加载指示器
                            officeViewer.removeChild(loadingIndicator);
                            
                            // 创建Word文档容器
                            const wordContainer = document.createElement('div');
                            wordContainer.className = 'word-document';
                            wordContainer.innerHTML = result.value;
                            
                            // 创建居中容器
                            const contentContainer = document.createElement('div');
                            contentContainer.className = 'doc-content-container';
                            contentContainer.appendChild(wordContainer);
                            
                            // 将内容容器添加到查看器
                            officeViewer.appendChild(contentContainer);
                            
                            // 如果有警告，可以在控制台记录
                            if (result.messages.length > 0) {
                                console.log('Word转换警告:', result.messages);
                            }
                        })
                        .catch(error => {
                            console.error('Word文档加载失败:', error);
                            officeViewer.style.display = 'none';
                            showFallbackViewer();
                        });
                } else {
                    // 对于老式doc格式，显示备用界面
                    officeViewer.removeChild(loadingIndicator);
                    const docFallback = document.createElement('div');
                    docFallback.style.padding = '30px';
                    docFallback.style.textAlign = 'center';
                    docFallback.style.maxWidth = '600px';
                    docFallback.style.margin = '0 auto';
                    
                    docFallback.innerHTML = `
                        <h2>此文档需要下载后查看</h2>
                        <p>此格式的文档无法在浏览器中直接预览。</p>
                        <p>请使用下载按钮保存到本地后查看。</p>
                        <a href="${url}" download class="download-btn">下载文档</a>
                    `;
                    
                    officeViewer.appendChild(docFallback);
                }
            }
            
            // Excel文档查看器
            function loadExcelViewer(url, fileType) {
                const officeViewer = document.getElementById('office-viewer');
                officeViewer.style.display = 'block';
                
                // 显示加载指示器
                const loadingIndicator = document.createElement('div');
                loadingIndicator.className = 'loading-indicator';
                loadingIndicator.innerHTML = `
                    <div class="loading-spinner"></div>
                    <p>正在加载电子表格，请稍候...</p>
                `;
                officeViewer.appendChild(loadingIndicator);
                
                // 获取Excel文档内容
                fetch(url)
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('无法加载电子表格');
                        }
                        return response.arrayBuffer();
                    })
                    .then(arrayBuffer => {
                        // 使用SheetJS解析Excel文档
                        const data = new Uint8Array(arrayBuffer);
                        const workbook = XLSX.read(data, { type: 'array' });
                        
                        // 移除加载指示器
                        officeViewer.removeChild(loadingIndicator);
                        
                        // 创建电子表格容器
                        const excelContainer = document.createElement('div');
                        excelContainer.style.padding = '20px';
                        excelContainer.className = 'doc-content-container';
                        
                        // 遍历所有工作表（默认最多显示前3个）
                        const maxSheets = Math.min(workbook.SheetNames.length, 3);
                        const sheetContainer = document.createElement('div');
                        
                        // 如果有多个工作表，创建选项卡导航
                        if (workbook.SheetNames.length > 1) {
                            const tabContainer = document.createElement('div');
                            tabContainer.style.display = 'flex';
                            tabContainer.style.borderBottom = '1px solid #ddd';
                            tabContainer.style.marginBottom = '15px';
                            
                            for (let i = 0; i < workbook.SheetNames.length; i++) {
                                const sheetName = workbook.SheetNames[i];
                                const tab = document.createElement('div');
                                tab.textContent = sheetName;
                                tab.style.padding = '10px 20px';
                                tab.style.cursor = 'pointer';
                                tab.style.backgroundColor = i === 0 ? '#f0f0f0' : 'transparent';
                                tab.style.borderBottom = i === 0 ? '2px solid #5E2D9B' : 'none';
                                tab.dataset.sheetIndex = i;
                                
                                tab.addEventListener('click', function() {
                                    // 显示选中的工作表
                                    const sheetIndex = parseInt(this.dataset.sheetIndex);
                                    document.querySelectorAll('.sheet-tab').forEach(tab => {
                                        tab.style.backgroundColor = 'transparent';
                                        tab.style.borderBottom = 'none';
                                    });
                                    this.style.backgroundColor = '#f0f0f0';
                                    this.style.borderBottom = '2px solid #5E2D9B';
                                    
                                    document.querySelectorAll('.sheet-content').forEach(sheet => {
                                        sheet.style.display = 'none';
                                    });
                                    document.getElementById(`sheet-${sheetIndex}`).style.display = 'block';
                                });
                                
                                tab.classList.add('sheet-tab');
                                tabContainer.appendChild(tab);
                            }
                            
                            excelContainer.appendChild(tabContainer);
                        }
                        
                        // 转换每个工作表为HTML表格
                        for (let i = 0; i < workbook.SheetNames.length; i++) {
                            const sheetName = workbook.SheetNames[i];
                            const worksheet = workbook.Sheets[sheetName];
                            
                            // 将工作表转换为HTML
                            const html = XLSX.utils.sheet_to_html(worksheet, { id: `table-${i}`, editable: false });
                            
                            // 创建工作表内容容器
                            const sheetContent = document.createElement('div');
                            sheetContent.id = `sheet-${i}`;
                            sheetContent.className = 'sheet-content';
                            sheetContent.style.display = i === 0 ? 'block' : 'none';
                            
                            // 添加工作表标题
                            if (workbook.SheetNames.length > 1) {
                                const sheetTitle = document.createElement('h3');
                                sheetTitle.textContent = sheetName;
                                sheetTitle.style.marginTop = '0';
                                sheetContent.appendChild(sheetTitle);
                            }
                            
                            // 添加表格到工作表容器
                            sheetContent.innerHTML += html;
                            
                            // 美化表格样式
                            const table = sheetContent.querySelector(`#table-${i}`);
                            if (table) {
                                table.className = 'excel-table';
                            }
                            
                            sheetContainer.appendChild(sheetContent);
                        }
                        
                        excelContainer.appendChild(sheetContainer);
                        
                        // 如果工作表太多，添加提示
                        if (workbook.SheetNames.length > 3) {
                            const moreInfo = document.createElement('div');
                            moreInfo.style.marginTop = '20px';
                            moreInfo.style.padding = '10px';
                            moreInfo.style.backgroundColor = '#f9f9f9';
                            moreInfo.style.borderRadius = '4px';
                            moreInfo.style.textAlign = 'center';
                            
                            moreInfo.innerHTML = `
                                <p>文档包含 ${workbook.SheetNames.length} 个工作表，请下载完整文档以查看全部内容。</p>
                                <a href="${url}" download class="download-btn" style="display:inline-block; margin-top:10px;">下载完整电子表格</a>
                            `;
                            
                            excelContainer.appendChild(moreInfo);
                        }
                        
                        officeViewer.appendChild(excelContainer);
                    })
                    .catch(error => {
                        console.error('Excel文档加载失败:', error);
                        officeViewer.style.display = 'none';
                        showFallbackViewer();
                    });
            }
            
            // 获取文档图标颜色
            function getIconColor(fileType) {
                const colorMap = {
                    'doc': '#2b579a',    // Word蓝
                    'docx': '#2b579a',
                    'xls': '#217346',    // Excel绿
                    'xlsx': '#217346',
                    'ppt': '#d24726',    // PPT橙红
                    'pptx': '#d24726',
                    'pdf': '#5E2D9B',    // PDF改为紫色
                    'default': '#5E2D9B'  // 默认紫色
                };
                
                return colorMap[fileType] || colorMap['default'];
            }
            
            // 备用查看器
            function showFallbackViewer(message = "无法直接预览此文档") {
                const fallbackViewer = document.getElementById('fallback-viewer');
                const messageElement = fallbackViewer.querySelector('.fallback-message p:first-child');
                if (messageElement) {
                    messageElement.textContent = message;
                }
                fallbackViewer.style.display = 'flex';
            }
        });
    </script>
</body>
</html> 